//
//  BuyCllowerViewController.m
//  jingdongfang
//
//  Created by 郝志宇 on 16/8/10.
//  Copyright © 2016年 ZhiYu Hao. All rights reserved.
//

#import "BuyCllowerViewController.h"
#import "BuySuccViewController.h"
#import "WeiXinPayManager.h"
#import "AliPayManager.h"
#import "BuyCllowerCell.h"
#import "IGSubmitOrderApi.h"
#import "IGPaymentResultQueryApi.h"
#import "OrderXQViewController.h"
#import "XiangQingViewController.h"
@interface BuyCllowerViewController () <UITableViewDelegate, UITableViewDataSource, SwitchChangeDelegate>
{
    UIView *header;
    NSInteger _payType;// 1支付宝 2微信
    NSInteger art_type;// 1单独支付 2混合支付
    NSString *orderId;// 订单id
    NSString *ifUseArtPoint;//是否使用艺点,1使用, 0不适用
}

@property (weak, nonatomic) IBOutlet UITableView *table;

@property (nonatomic, strong)UIView *buyView;
@property (nonatomic, strong)UILabel *moneyL;
@property (nonatomic, copy)NSString *artCion;//艺点

@end

@implementation BuyCllowerViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
//    self.title = @"限量收藏";
    self.title = NSLocalizedString(@"Limited Collect", nil);
    
    _payType = (_type == 2 ) ? 1 : 1;
    art_type = 1;
    self.table.backgroundColor = [UIColor c2Color];
    self.table.tableHeaderView = header;
    
    self.table.contentInset = UIEdgeInsetsMake(0, 0, 44, 0);
    self.table.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 44, 0);
    [self.table mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(-44);
        make.top.mas_equalTo(0);
    }];
    [self.table registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
    [self.table registerNib:[UINib nibWithNibName:@"BuyCllowerCell" bundle:nil] forCellReuseIdentifier:@"BuyCllowerCell"];
    
    [self initBuyView];

    //注册监听-支付宝
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(dealAlipayResult:) name:@"alipayResult" object:nil];
    //注册监听-微信
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(dealWXpayResult:) name:@"WXpayresult" object:nil];
    self.artCion = _model.artPoint;
    [self priceChange];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //注册监听-微信
    //    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(dealWXpayResult:) name:@"WXpayresult" object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    //    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)initBuyView
{
    self.buyView = [[UIView alloc] init];
    self.buyView.bottom = KSCREENHEIGHT;
    self.buyView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.buyView];
    [self.buyView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.height.mas_equalTo(44);
    }];
    
    self.moneyL = [[UILabel alloc] init];
    self.moneyL.numberOfLines = 0;
    self.moneyL.textColor = [UIColor c1Color];
    self.moneyL.font = [UIFont systemFontOfSize:20];
    self.moneyL.textAlignment = NSTextAlignmentRight;
    [self.buyView addSubview:self.moneyL];
    [self.moneyL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.top.bottom.mas_equalTo(0);
        make.width.mas_equalTo(KSCREENWIDTH / 3 * 2 - 20);
    }];
    
    UIButton *buy = [UIButton buttonWithType:UIButtonTypeCustom];
    buy.backgroundColor = [UIColor c1Color];
//    [buy setTitle:@"去付款" forState:UIControlStateNormal];
    [buy setTitle: NSLocalizedString(@"Go to the payment", nil) forState:UIControlStateNormal];
    [buy setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [buy addTarget:self action:@selector(subOrder:) forControlEvents:UIControlEventTouchUpInside];
    buy.titleLabel.font = [UIFont systemFontOfSize:16];
    [self.buyView addSubview:buy];
    [buy mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.right.mas_equalTo(0);
        make.width.mas_equalTo(KSCREENWIDTH / 3);
    }];
 
}


- (void)priceChange
{
    if (_type == 2)
    {
        //        self.moneyL.text = [NSString stringWithFormat:@"艺点已抵扣: ¥%.2f 应付: ¥%.2f", _model.artPointActual.floatValue/10, _model.priceActual.floatValue];
//        self.moneyL.text = [NSString stringWithFormat:@"应付: ¥%.2f", _model.priceActual.floatValue];
        self.moneyL.text = [NSString stringWithFormat:@"%@: ¥%.2f", NSLocalizedString(@"Payment", nil),_model.priceActual.floatValue];
        self.moneyL.font = [UIFont font14];
        ifUseArtPoint = @"";
        art_type = 1;
    }
    else
    {
//        BuyCllowerCell *cell = (BuyCllowerCell *)[self.table cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
        /*
         if (_artCion && [_artCion floatValue] > 0)
         {
         //艺点足够时采用单一支付方式
         if (_artCion.floatValue/10 >= _model.price.floatValue)
         {
         ifUseArtPoint = @"1";
         art_type = 1;
         cell.textL.text = [NSString stringWithFormat:@"共%.1f艺点, 本次抵扣¥ %.2f", _artCion.floatValue, _model.price.floatValue];
         }
         else//艺点不够时采用混合支付方式
         {
         art_type = 2;
         ifUseArtPoint = @"1";
         cell.textL.text = [NSString stringWithFormat:@"共%.1f艺点, 本次抵扣¥ %.2f", _artCion.floatValue, _artCion.floatValue/10];
         }
         cell.switchBtn.on = YES;
         cell.switchBtn.userInteractionEnabled = YES;
         }
         else//无艺点, 第三方支付
         {
         art_type = 1;
         ifUseArtPoint = @"0";
         cell.textL.text = [NSString stringWithFormat:@"无艺点可用"];
         cell.switchBtn.on = NO;
         cell.switchBtn.userInteractionEnabled = NO;
         }
         */
        art_type = 1;
        ifUseArtPoint = @"0";
        self.moneyL.text = [NSString stringWithFormat:@"%@: ¥%.2f", NSLocalizedString(@"Actual Payment", nil),[_model.price floatValue]];
//        cell.textL.text = [NSString stringWithFormat:@"无艺点可用"];
//        cell.switchBtn.on = NO;
//        cell.switchBtn.userInteractionEnabled = NO;
//        [self switchIsOn:cell.switchBtn.isOn];
    }
}

- (void)switchIsOn:(BOOL)on
{
    UITableViewCell *cell1 = [self.table cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    UITableViewCell *cell2 = [self.table cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
    if (on)//使用艺点支付
    {
        if (art_type == 1)//艺点足够时采用单一支付方式
        {
            cell1.selectionStyle = UITableViewCellSelectionStyleNone;
            cell2.selectionStyle = UITableViewCellSelectionStyleNone;
            _payType = 0;
            [self.table reloadData];
//            self.moneyL.text = [NSString stringWithFormat:@"实付款: ¥0.00"];
            self.moneyL.text = [NSString stringWithFormat:@"%@: ¥0.00",NSLocalizedString(@"Actual Payment",nil)];
        }
        else if (art_type == 2)//艺点不够时采用混合支付方式
        {
            cell1.userInteractionEnabled = YES;
            cell2.userInteractionEnabled = YES;
            _payType = 1;
            [self.table reloadData];
            self.moneyL.text = [NSString stringWithFormat:@"%@: ¥%.2f", NSLocalizedString(@"Actual Payment",nil),[_model.price floatValue] - [_artCion floatValue]/10];
        }
        ifUseArtPoint = @"1";
    }
    else
    {
        cell1.userInteractionEnabled = YES;
        cell2.userInteractionEnabled = YES;
        _payType = 1;
        [self.table reloadData];
        self.moneyL.text = [NSString stringWithFormat:@"%@: ¥%.2f", NSLocalizedString(@"Actual Payment",nil),[_model.price floatValue]];
        ifUseArtPoint = @"0";
    }
}


- (void)subOrder:(UIButton *)btn
{
//    [self showText:@"正在提交订单"];
    [self showText:NSLocalizedString(@"Order Submitting", nil)];

    IGSubmitOrderApi *api = [IGSubmitOrderApi new];
    api.orderContent = @"";
    api.worksId = _model.worksId;
    api.orderId = (_type == 2) ? _model.orderId : @"";
    NSString *str = @"";
    if (_payType == 1)
    {
        str = @"alipay";
    }
    else if (_payType == 2)
    {
        str = @"wxpay";
    }
    api.payPlatCode = str;
    api.ifUseArtPoint = (_type == 2) ? @"" : ifUseArtPoint;
    
    @KWeakObj(self)
    [api startWithDecodeClass:[IGSubmitOrderResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject)
        {
            [selfWeak dismissLoading];
            IGSubmitOrderResp *resp = responseObject;
            IGSubmitOrderModel *submitOrderModel = resp.data;
            if ([submitOrderModel.method isEqualToString:@"paySuccess"])
            {
                BuySuccViewController *vc = [[BuySuccViewController alloc] initWithNibName:@"BuySuccViewController" bundle:nil];
                @KWeakObj(vc)
                orderId = submitOrderModel.orderId;
                vc.orderId = orderId;
                vc.backBtnClick = ^{
                    [UIViewController ig_popViewController:[XiangQingViewController class]];
                };
                vc.orderBtnClick = ^{
                    [vcWeak back];
                    OrderXQViewController *vc1 = [[OrderXQViewController alloc] init];
                    vc1.oid = orderId;
                    vc1.isMyBuy = YES;
                    [UIViewController ig_pushViewController:vc1 animated:YES];
                };
                [selfWeak presentViewController:vc animated:YES completion:nil];
            }
            else
            {
                orderId = submitOrderModel.orderId;
                if (_payType == 1)
                {
                    [[AliPayManager sharedAliPayManager] payWithDic:submitOrderModel.ResBean];
                    return;
                }
                else if (_payType == 2)
                {
                    NSDictionary *dic = submitOrderModel.ResBean[@"data"];
                    if (dic)
                    {
                        WXProduct * wx  = [WXProduct new];
                        wx.package = dic[@"package"];
                        wx.noncestr = dic[@"noncestr"];
                        wx.appid = dic[@"appid"];
                        wx.partnerid = dic[@"partnerid"];
                        wx.prepayid = dic[@"prepayid"];
                        wx.timestamp = [dic[@"timestamp"] longLongValue];
                        wx.sign = dic[@"sign"];
                        [[WeiXinPayManager sharedManager]weiXinPay:wx];
                        return;
                    }
                }
            }
        }
    }];
    
}

#pragma mark - 支付宝支付状态回调
-(void)dealAlipayResult:(NSNotification*)notification{
    NSString*result=notification.object;
    if([result isEqualToString:@"9000"]){
        //在这里写支付成功之后的回调操作
//        NSLog(@"支付宝支付成功");
        IGPaymentResultQueryApi *api = [IGPaymentResultQueryApi new];
        api.orderId = orderId;
        api.worksId = _model.worksId;
        api.payPlatCode = @"alipay";
        [api startWithDecodeClass:[IGPaymentResultQueryResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
            
        }];
        @KWeakObj(self)
        BuySuccViewController *vc = [[BuySuccViewController alloc] initWithNibName:@"BuySuccViewController" bundle:nil];
        @KWeakObj(vc)
        vc.orderId = orderId;
        vc.backBtnClick = ^{
            [selfWeak.navigationController popViewControllerAnimated:YES];
        };
        vc.orderBtnClick = ^{
            [vcWeak back];
            OrderXQViewController *vc1 = [[OrderXQViewController alloc] init];
            vc1.oid = orderId;
            vc1.isMyBuy = YES;
            [UIViewController ig_pushViewController:vc1 animated:YES];
        };
        [selfWeak presentViewController:vc animated:YES completion:nil];
    }
    else
    {
        //在这里写支付失败之后的回调操作
        //DeLog(@"支付宝支付失败");
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - 微信支付状态的回调

-(void)dealWXpayResult:(NSNotification*)notification{
    NSString*result=notification.object;
    if([result isEqualToString:@"1"])
    {
        //在这里写支付成功之后的回调操作
//        NSLog(@"微信支付成功");
        IGPaymentResultQueryApi *api = [IGPaymentResultQueryApi new];
        api.orderId = orderId;
        api.worksId = _model.worksId;
        api.payPlatCode = @"wxpay";
        [api startWithDecodeClass:[IGPaymentResultQueryResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
            if (responseObject)
            {
            }
        }];
        @KWeakObj(self)
        BuySuccViewController *vc = [[BuySuccViewController alloc] initWithNibName:@"BuySuccViewController" bundle:nil];
        @KWeakObj(vc)
        vc.orderId = orderId;
        vc.backBtnClick = ^{
            [selfWeak.navigationController popViewControllerAnimated:YES];
        };
        vc.orderBtnClick = ^{
            [vcWeak back];
            OrderXQViewController *vc1 = [[OrderXQViewController alloc] init];
            vc1.oid = orderId;
            vc1.isMyBuy = YES;
            [UIViewController ig_pushViewController:vc1 animated:YES];
        };
        [selfWeak presentViewController:vc animated:YES completion:nil];
    }else{
        //在这里写支付失败之后的回调操作
        // DeLog(@"微信支付失败");
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)setModel:(IGAddOrderModel *)model
{
    if (_model != model)
    {
        _model = model;
    }
    CGFloat wid = 80;
    header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, wid+40)];
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 0, wid, wid)];
    imgView.centerY = header.height/2;
    imgView.backgroundColor = [UIColor c2Color];
    imgView.contentMode = UIViewContentModeScaleAspectFill;
    imgView.clipsToBounds = YES;
    [imgView sd_setImageWithURL:[NSURL URLWithString:_model.image]];
    [header addSubview:imgView];
    
    UILabel *name = [[UILabel alloc] initWithFrame:CGRectZero];
    name.text = _model.title?:@" ";
    name.font = [UIFont boldSystemFontOfSize:16];
    name.textColor = [UIColor c4Color];
    name.x = imgView.right + 10;
    name.top = imgView.top+2;
    [name sizeToFit];
    [header addSubview:name];
    name.width = KSCREENWIDTH - name.left - 10;
    name.numberOfLines = 0;
    CGSize si = [Tool getLabelSizeWithText:name.text AndWidth:name.width AndFont:name.font attribute:nil];
    name.height = si.height;
    
    UILabel *author = [[UILabel alloc] initWithFrame:CGRectZero];
    author.text = _model.seller;
    author.font = [UIFont systemFontOfSize:14];
    author.textColor = [UIColor c5Color];
    [header addSubview:author];
    [author sizeToFit];
    author.x = imgView.right + 10;
    author.top = name.bottom + 8;
    //    UILabel *num = [[UILabel alloc] initWithFrame:CGRectZero];
    //    num.text = [NSString stringWithFormat:@"%@人收藏/%@", info.electronics_nume.length>0?info.electronics_nume:@"0", [info.electronic_nums integerValue]>0?info.electronic_nums:@"无限制"];
    //    num.font = [UIFont systemFontOfSize:15];
    //    num.textColor = [UIColor blackColor];
    //    [header addSubview:num];
    //    [num sizeToFit];
    //    num.x = imgView.right + 10;
    //    num.top = author.bottom + 8;
    
    UILabel *price = [[UILabel alloc] initWithFrame:CGRectZero];
    price.text = [@"￥" stringByAppendingString:_model.price.length>0?_model.price:@"0"];
    price.font = [UIFont boldSystemFontOfSize:14];
    price.textColor = [UIColor c1Color];
    [header addSubview:price];
    [price sizeToFit];
    price.right = KSCREENWIDTH - 20;
    price.y = author.y;
    author.width =  KSCREENWIDTH - author.left - 10-price.width-8;
    self.table.tableHeaderView = header;
}


#pragma mark - UITableViewDelegate, UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //    return (_type == 2) ? 1 : 2;
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
    {
        return 3;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"UITableViewCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        cell.textLabel.textColor = [UIColor c4Color];
        CGFloat h = [self tableView:tableView heightForRowAtIndexPath:indexPath];
        
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 0, 35, 35)];
        imgView.centerY = h/2;
        imgView.contentMode = UIViewContentModeScaleAspectFit;
        
        UIImageView *acc = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
        acc.contentMode = UIViewContentModeScaleAspectFit;
        
        UILabel *title = [[UILabel alloc] initWithFrame:CGRectZero];
        title.font = [UIFont systemFontOfSize:15];
        title.textColor = [UIColor c4Color];

        if (indexPath.row==0)
        {
            cell.textLabel.text = NSLocalizedString(@"Select Payment Method", nil);
        }
        else if (indexPath.row==1)
        {
            imgView.image = [UIImage imageNamed:@"APP buy 切图 20160727-4"];
            [cell.contentView addSubview:imgView];
            title.text = NSLocalizedString(@"Alipay", nil);
            [title sizeToFit];
            [cell.contentView addSubview:title];
            title.centerY = h/2;
            title.left = imgView.right + 18;
            if (_payType == 1)
            {
                acc.image = [UIImage imageNamed:@"未标题-1-2"];
            }
            else
            {
                acc.image = [UIImage imageNamed:@"未标题-1-1"];
            }
            cell.accessoryView = acc;
            UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(title.x, 0, KSCREENWIDTH-title.x, 0.5f)];
            line.backgroundColor = [UIColor c6Color];
            [cell.contentView addSubview:line];
        }
        else if (indexPath.row==2)
        {
            imgView.image = [UIImage imageNamed:@"APP buy 切图 20160727-5"];
            [cell.contentView addSubview:imgView];
            title.text = NSLocalizedString(@"WeChat", nil);
            [title sizeToFit];
            [cell.contentView addSubview:title];
            title.centerY = h/2;
            title.left = imgView.right + 18;
            if (_payType == 2)
            {
                acc.image = [UIImage imageNamed:@"未标题-1-2"];
            }
            else
            {
                acc.image = [UIImage imageNamed:@"未标题-1-1"];
            }
            cell.accessoryView = acc;
            UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(title.x, 0, KSCREENWIDTH-title.x, 0.5)];
            line.backgroundColor = [UIColor c6Color];
            [cell.contentView addSubview:line];
        }
        return cell;
    }
    else if (indexPath.section == 1)
    {
        BuyCllowerCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BuyCllowerCell" forIndexPath:indexPath];
        cell.delegate = self;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//    if (_type == 2)
//    {
        if (indexPath.section == 0 && indexPath.row!=0 )
        {
            _payType = indexPath.row;
            [tableView reloadData];
        }
//    }
//    else
//    {
//        BuyCllowerCell *cell = (BuyCllowerCell *)[self.table cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
//        if (cell.switchBtn.isOn && art_type == 1)//使用艺点支付
//        {
//            //无响应
//        }
//        else
//        {
//            if (indexPath.section == 0 && indexPath.row!=0 )
//            {
//                _payType = indexPath.row;
//                [tableView reloadData];
//            }
//        }
//    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row==0)
    {
        return 35;
    }
    return 55;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 1)
    {
        return 10;
    }
    return .1f;
}

@end

